<template>
  <a-button 
 
    type="primary" 
    size="large" 
    class="clone-btn" 
    @click="handleCloneVoice"
    :loading="loading"
  >
    <template #icon>
      <Copy :size="16" />
    </template>
    音色克隆
  </a-button>

  <!-- 音色克隆弹窗 -->
  <a-modal
    :open="modalVisible"
    title="音色克隆"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="600px"
    ok-text="开始克隆"
    cancel-text="取消操作"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
    >
      <a-form-item label="音色名称" name="voiceName">
        <a-input
          v-model:value="formData.voiceName"
          placeholder="请输入音色名称"
          :maxlength="50"
        />
      </a-form-item>

      <a-form-item label="音色类型" name="type">
        <a-radio-group v-model:value="formData.type">
          <a-radio :value="0">女声</a-radio>
          <a-radio :value="1">男声</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="音色描述" name="description">
        <a-textarea
          v-model:value="formData.description"
          placeholder="请输入音色描述"
          :rows="3"
          :maxlength="200"
          show-count
        />
      </a-form-item>

      <a-form-item label="音色参数" name="voiceParam">
        <a-input
          v-model:value="formData.voiceParam"
          placeholder="用于添加第三方音色的参数（可选）"
          :maxlength="100"
        />
      </a-form-item>

      <a-form-item label="音色文件" name="voiceFileUrl">
        <div class="upload-area">
          <a-upload
            :file-list="fileList"
            :before-upload="beforeUpload"
            :remove="handleRemove"
            accept=".mp3,.wav,.m4a"
            :max-count="1"
          >
            <a-button>
              <UploadOutlined />
              选择音频文件
            </a-button>
          </a-upload>
          <div class="upload-tip">
            支持 MP3、WAV、M4A 格式，文件大小不超过 10MB
          </div>
          <a-input
            v-model:value="formData.voiceFileUrl"
            placeholder="或直接输入音频文件URL"
            style="margin-top: 8px;"
          />
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import { Copy} from 'lucide-vue-next'
import { UploadOutlined } from '@ant-design/icons-vue'
import type { FormInstance, UploadFile } from 'ant-design-vue'
import type { VoiceAddDto } from '@/api/generated/data-contracts'
import { Codewin } from '@/api/generated/Codewin'
import { useAuthStore, useUserStore } from '@/stores'

interface Emits {
  (e: 'success'): void
}

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const modalVisible = ref(false)
const fileList = ref<UploadFile[]>([])

// 获取用户状态
const authStore = useAuthStore()
const userStore = useUserStore()

// 管理员权限检查
const isAdmin = computed(() => userStore.isAdmin)

// 表单数据
const formData = reactive<VoiceAddDto>({
  voiceName: '',
  voiceParam: '',
  description: '',
  voiceFileUrl: '',
  type: 0
})

// 表单验证规则
const rules = {
  voiceName: [
    { required: true, message: '请输入音色名称', trigger: 'blur' },
    { min: 1, max: 50, message: '音色名称长度为1-50个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入音色描述', trigger: 'blur' },
    { min: 1, max: 200, message: '音色描述长度为1-200个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择音色类型', trigger: 'change' }
  ]
}

// API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  securityWorker: () => ({
    headers: authStore.token ? { Authorization: `Bearer ${authStore.token}` } : {}
  })
})

// 点击音色克隆按钮
const handleCloneVoice = () => {
  // 双重检查管理员权限
  // if (!userStore.isAdmin) {
  //   message.error('只有管理员才能使用音色克隆功能')
  //   return
  // }
  modalVisible.value = true
}

// 文件上传前处理
const beforeUpload = async (file: File) => {
  const isAudio = file.type.startsWith('audio/')
  if (!isAudio) {
    message.error('只能上传音频文件！')
    return false
  }

  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('音频文件大小不能超过 2MB！')
    return false
  }

  try {
    loading.value = true
    const uploadFormData = new FormData()
    uploadFormData.append('file', file)
    
    const response = await api.uploadFile({ file })
    if (response.data?.code === 0) {
      formData.voiceFileUrl = response.data.data || ''
      fileList.value = [{
        uid: file.name,
        name: file.name,
        status: 'done',
        url: response.data.data
      }]
      message.success('文件上传成功')
    } else {
      message.error(response.data?.message || '文件上传失败')
    }
  } catch (error) {
    console.error('文件上传失败:', error)
    message.error('文件上传失败')
  } finally {
    loading.value = false
  }

  return false // 阻止默认上传行为
}

// 移除文件
const handleRemove = () => {
  formData.voiceFileUrl = ''
  fileList.value = []
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    // 克隆音色（新增音色）
    const response = await api.addVoice(formData)
    if (response.data?.code === 0) {
      message.success('音色克隆成功')
      emit('success')
      handleCancel()
    } else {
      message.error(response.data?.message || '音色克隆失败')
    }
  } catch (error) {
    console.error('音色克隆失败:', error)
    message.error('音色克隆失败，请重试')
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    voiceName: '',
    voiceParam: '',
    description: '',
    voiceFileUrl: '',
    type: 0
  })
  fileList.value = []
}
</script>

<style scoped>
.clone-btn {
  background: linear-gradient(135deg, #8b5cf6 0%, #a78bfa 100%);
  border-color: #8b5cf6;
  box-shadow: 0 2px 8px rgba(139, 92, 246, 0.3);
  transition: all 0.3s ease;
}

.clone-btn:hover {
  background: linear-gradient(135deg, #7c3aed 0%, #8b5cf6 100%);
  border-color: #7c3aed;
  box-shadow: 0 4px 12px rgba(139, 92, 246, 0.4);
  transform: translateY(-1px);
}

.clone-btn:focus {
  background: linear-gradient(135deg, #8b5cf6 0%, #a78bfa 100%);
  border-color: #8b5cf6;
}

.upload-area {
  width: 100%;
}

.upload-tip {
  margin-top: 8px;
  color: #666;
  font-size: 12px;
}

:deep(.ant-upload-list) {
  margin-top: 8px;
}
</style>